package com.abaaba.project2.service.serviceImpl;

import com.abaaba.project2.bean.Address;
import com.abaaba.project2.bean.AddressExample;
import com.abaaba.project2.bean.vo.AddressVo;
import com.abaaba.project2.bean.vo.AdminAddressVo;
import com.abaaba.project2.mapper.AddressMapper;
import com.abaaba.project2.mapper.RegionMapper;
import com.abaaba.project2.service.AdminAddressService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class AdminAddressServiceImpl implements AdminAddressService {
    @Autowired
    AddressMapper addressMapper;
    @Autowired
    RegionMapper regionMapper;

    @Override
    public AdminAddressVo getAddressList(Integer page, Integer limit, Integer userId, String name, String sort, String order) {
        PageHelper.startPage(page, limit);

        AddressExample addressExample = new AddressExample();
        addressExample.setOrderByClause(sort + " " + order);

        // 根据条件筛选数据库地址表
        AddressExample.Criteria criteria = addressExample.createCriteria();
        criteria.andDeletedEqualTo(false);
        if (userId != null) {
            criteria.andUserIdEqualTo(userId);
        }
        if (name != null && !"".equals(name)) {
            criteria.andNameLike("%" + name + "%");
        }
        List<Address> addressList = addressMapper.selectByExample(addressExample);

        List<AddressVo> addressVos = new ArrayList<>();
        for (Address address : addressList) {
            String province = regionMapper.selectByPrimaryKey(address.getProvinceId()).getName();
            String city = regionMapper.selectByPrimaryKey(address.getCityId()).getName();
            String area = regionMapper.selectByPrimaryKey(address.getAreaId()).getName();

            AddressVo addressVo = new AddressVo(area, address.getIsDefault(), address.getAreaId(), address.getAddress(),
                    province, city, address.getName(), address.getMobile(), address.getId(), address.getCityId(),
                    address.getUserId(), address.getProvinceId());

            addressVos.add(addressVo);
        }

        // 分页信息
        PageInfo<Address> addressVoPageInfo = new PageInfo<>(addressList);
        long total = addressVoPageInfo.getTotal();

        // 返回前端的对象
        AdminAddressVo adminAddressVo = new AdminAddressVo();
        adminAddressVo.setTotal((int)total);
        adminAddressVo.setItems(addressVos);

        return adminAddressVo;
    }
}
